// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <pollux/functions/prestosql/aggregates/count_aggregate.h>
#include <pollux/common/base/exceptions.h>
#include <pollux/expression/function_signature.h>
#include <pollux/functions/lib/aggregates/sum_aggregate_base.h>
#include <pollux/functions/prestosql/aggregates/aggregate_names.h>

using namespace kumo::pollux::functions::aggregate;

namespace kumo::pollux::aggregate::prestosql {
    namespace {
        class CountAggregate : public SimpleNumericAggregate<bool, int64_t, int64_t> {
            using BaseAggregate = SimpleNumericAggregate<bool, int64_t, int64_t>;

        public:
            explicit CountAggregate() : BaseAggregate(BIGINT()) {
            }

            int32_t accumulatorFixedWidthSize() const override {
                return sizeof(int64_t);
            }

            void extractValues(char **groups, int32_t numGroups, VectorPtr *result)
            override {
                BaseAggregate::doExtractValues(groups, numGroups, result, [&](char *group) {
                    return *value<int64_t>(group);
                });
            }

            void addRawInput(
                char **groups,
                const SelectivityVector &rows,
                const std::vector<VectorPtr> &args,
                bool /*mayPushdown*/) override {
                if (args.empty()) {
                    rows.applyToSelected([&](vector_size_t i) { addToGroup(groups[i], 1); });
                    return;
                }

                DecodedVector decoded(*args[0], rows);
                if (decoded.isConstantMapping()) {
                    if (!decoded.is_null_at(0)) {
                        rows.applyToSelected(
                            [&](vector_size_t i) { addToGroup(groups[i], 1); });
                    }
                } else if (decoded.may_have_nulls()) {
                    rows.applyToSelected([&](vector_size_t i) {
                        if (decoded.is_null_at(i)) {
                            return;
                        }
                        addToGroup(groups[i], 1);
                    });
                } else {
                    rows.applyToSelected([&](vector_size_t i) { addToGroup(groups[i], 1); });
                }
            }

            void addIntermediateResults(
                char **groups,
                const SelectivityVector &rows,
                const std::vector<VectorPtr> &args,
                bool /*mayPushdown*/) override {
                decodedIntermediate_.decode(*args[0], rows);
                rows.applyToSelected([&](vector_size_t i) {
                    addToGroup(groups[i], decodedIntermediate_.value_at<int64_t>(i));
                });
            }

            void addSingleGroupRawInput(
                char *group,
                const SelectivityVector &rows,
                const std::vector<VectorPtr> &args,
                bool /*mayPushdown*/) override {
                if (args.empty()) {
                    addToGroup(group, rows.countSelected());
                    return;
                }

                DecodedVector decoded(*args[0], rows);
                if (decoded.isConstantMapping()) {
                    if (!decoded.is_null_at(0)) {
                        addToGroup(group, rows.countSelected());
                    }
                } else if (decoded.may_have_nulls()) {
                    int64_t nonNullCount = 0;
                    rows.applyToSelected([&](vector_size_t i) {
                        if (!decoded.is_null_at(i)) {
                            ++nonNullCount;
                        }
                    });
                    addToGroup(group, nonNullCount);
                } else {
                    addToGroup(group, rows.countSelected());
                }
            }

            void addSingleGroupIntermediateResults(
                char *group,
                const SelectivityVector &rows,
                const std::vector<VectorPtr> &args,
                bool /*mayPushdown*/) override {
                decodedIntermediate_.decode(*args[0], rows);

                int64_t count = 0;
                if (decodedIntermediate_.may_have_nulls()) {
                    rows.applyToSelected([&](vector_size_t i) {
                        if (!decodedIntermediate_.is_null_at(i)) {
                            count += decodedIntermediate_.value_at<int64_t>(i);
                        }
                    });
                } else {
                    rows.applyToSelected([&](vector_size_t i) {
                        count += decodedIntermediate_.value_at<int64_t>(i);
                    });
                }

                addToGroup(group, count);
            }

        protected:
            void initializeNewGroupsInternal(
                char **groups,
                melon::Range<const vector_size_t *> indices) override {
                for (auto i: indices) {
                    // result of count is never null
                    *value<int64_t>(groups[i]) = static_cast<int64_t>(0);
                }
            }

        private:
            inline void addToGroup(char *group, int64_t count) {
                *value<int64_t>(group) += count;
            }

            DecodedVector decodedIntermediate_;
        };
    } // namespace

    void registerCountAggregate(
        const std::string &prefix,
        bool withCompanionFunctions,
        bool overwrite) {
        std::vector<std::shared_ptr<exec::AggregateFunctionSignature> > signatures{
            exec::AggregateFunctionSignatureBuilder()
            .returnType("bigint")
            .intermediateType("bigint")
            .build(),
            exec::AggregateFunctionSignatureBuilder()
            .typeVariable("T")
            .returnType("bigint")
            .intermediateType("bigint")
            .argumentType("T")
            .build(),
        };

        auto name = prefix + kCount;
        exec::registerAggregateFunction(
            name,
            std::move(signatures),
            [name](
        core::AggregationNode::Step step,
        const std::vector<TypePtr> &argTypes,
        const TypePtr & /*resultType*/,
        const core::QueryConfig & /*config*/)
        -> std::unique_ptr<exec::Aggregate> {
                POLLUX_CHECK_LE(
                    argTypes.size(), 1, "{} takes at most one argument", name);
                return std::make_unique<CountAggregate>();
            },
            {false /*orderSensitive*/, false /*companionFunction*/},
            withCompanionFunctions,
            overwrite);
    }
} // namespace kumo::pollux::aggregate::prestosql
